package com.zhaoyue.study.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/2/4
 * Time: 17:32
 * To change this template use File | Settings | File Templates.
 */
public class StudentCgLibProxy implements MethodInterceptor{
    private Enhancer enhancer = new Enhancer();
    public Object getProxy(Class clazz){
        //设置要创建的子类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //根据字节码技术生成子类实例
        return enhancer.create();
    }



    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置");
        Object result =  methodProxy.invokeSuper(o,objects);
        System.out.println("后置");
        return result;
    }

    public static void main(String[] args) {
        StudentCgLibProxy studentCgLibProxy = new StudentCgLibProxy();
        StudentServiceImpl studentService = (StudentServiceImpl)studentCgLibProxy.getProxy(StudentServiceImpl.class);
        studentService.addStudent();
    }
}
